package com.carloha.finance.tool;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil3 {
	
	static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);
	public static final String  charset = "UTF-8";
	
	/**
	 * 发送get请求,  下载图片
	 * 
	 * @param url
	 *            路径
	 * @return
	 */
	public static void httpGetImg(CloseableHttpClient client,String imgUrl,String savePath) {		 
		// 发送get请求
		HttpGet request = new HttpGet(imgUrl);
		// 设置请求和传输超时时间
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(50000).setConnectTimeout(50000).build();		
		//设置请求头
		request.setHeader( "User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1" );		
		request.setConfig(requestConfig);
		try {
			CloseableHttpResponse response = client.execute(request);			
			 if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { 
				  HttpEntity entity = response.getEntity();  				  
				  InputStream in = entity.getContent();  				  
				  FileUtils.copyInputStreamToFile(in, new File(savePath));
				  System.out.println("下载图片成功:"+imgUrl);
				  
			 }
			 
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			request.releaseConnection();
			
		}
	}
	
	public static CloseableHttpClient getHttpClient() {		
		return HttpClients.createDefault();
	}
	
	public static void closeHttpClient(CloseableHttpClient client) {
		 try {
			 if(client != null) {
				 client.close();
			 }
		 }catch(Exception e) {
			 LOG.info("e:"+e);
		 }
	}
	
	public static void main(String[] args) {
		String url = "https://static.dingtalk.com/media/lADPDgQ9q0S9lobNA8DNBQA_1280_960.jpg";
		String file = "lADPDgQ9q0S9lobNA8DNBQA_1280_960.jpg";
		String path = EnvUtil.getPath();
		
		CloseableHttpClient client = null;
		try {
			client = getHttpClient();
			httpGetImg(client,url,path+"/"+file);
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeHttpClient(client);
		}
		
		
	}
}
